package com.jyy.prefabricated.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.CourseStudyTimeTecordDto;
import com.jyy.prefabricated.dto.Pageable;
import com.jyy.prefabricated.dto.StudentRecordExcelDto;
import com.jyy.prefabricated.entity.SysUser;
import com.jyy.prefabricated.enums.UserTypeEnum;
import com.jyy.prefabricated.service.CourseStudyTimeTecordService;
import com.jyy.prefabricated.utils.ExcelUtil;
import com.jyy.prefabricated.utils.UserUtils;
import com.jyy.prefabricated.vo.CoursePackageTecordVo;
import com.jyy.prefabricated.vo.CourseStudyTimeTecordVo;
import com.jyy.prefabricated.vo.StudentQuizRecordVo;
import com.jyy.prefabricated.vo.StudentStudyTimeTecordVo;
import junit.framework.Test;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 企业查询课程学习学时记录控制层
 *
 * @author makejava
 * @since 2021-10-11 13:49:02
 */
@RestController
@RequestMapping("/api")
public class CourseStudyTimeTecordController {
    /**
     * 服务对象
     */
    @Resource
    private CourseStudyTimeTecordService courseStudyTimeTecordService;

    @Resource
    private UserUtils userUtils;

    /**
     * 企业所购买课程包二级专项列表
     *
     * @param dto 主键
     * @return 单条数据
     */
    @GetMapping("/course-record")
    public AjaxResult selectCourseStudyTimeTecord(CourseStudyTimeTecordDto dto) {
        SysUser user = userUtils.getCurrentUser();
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            dto.setTrainingOrganizationId(user.getTrainingOrganization().getId());
        }

        List<CourseStudyTimeTecordVo> list = courseStudyTimeTecordService.selectCourseStudyTimeTecord(dto);

        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<CourseStudyTimeTecordVo> studentQuizVoList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (CourseStudyTimeTecordVo item : list) {
                if (item.getPurchaseCount() != null && item.getPurchaseCount() > 0) {
                    studentQuizVoList.add(item);
                }
            }
        }
        PageInfo<CourseStudyTimeTecordVo> result = new PageInfo<>(studentQuizVoList);
        return AjaxResult.success(result);
    }


    /**
     * 企业所购买课程包二级专项详情列表
     *
     * @param categoryId 主键
     * @return 单条数据
     */
    @GetMapping("/course-record-list/{categoryId}")
    public AjaxResult selectByCategoryId(@PathVariable Integer categoryId, Pageable pageable) throws IOException, NoSuchAlgorithmException {
        SysUser user = userUtils.getCurrentUser();
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<CoursePackageTecordVo> list = courseStudyTimeTecordService.selectByCategoryIdAndTrainingOrganizationId(user.getTrainingOrganization().getId(), categoryId);
        PageInfo<CoursePackageTecordVo> result = new PageInfo<>(list);
        return AjaxResult.success(result);
    }


    /**
     * 企业所购买课程包学员学习记录列表
     *
     * @param orderId 主键
     * @return 单条数据
     */
    @GetMapping("/student-record-list/{orderId}")
    public AjaxResult selectByOrderId(@PathVariable Integer orderId, Pageable pageable) {
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<StudentStudyTimeTecordVo> list = courseStudyTimeTecordService.selectByOrderId(orderId);
        PageInfo<StudentStudyTimeTecordVo> result = new PageInfo<>(list);
        return AjaxResult.success(result);
    }


    /**
     * 企业所购买课程包学员学习记录列表(导出)
     *
     * @return
     */
    @PostMapping("/student-record-excel")
    public void downloadRecordExcel(@RequestBody StudentRecordExcelDto dto, HttpServletResponse response) {

        if (dto.getType() == 1) {
            List<StudentStudyTimeTecordVo> list = courseStudyTimeTecordService.selectByOrderId(dto.getOrderId());
            downloadExcel(list, response);
        } else {
            List<StudentStudyTimeTecordVo> list = courseStudyTimeTecordService.selectByOrderId(dto.getOrderId());
            if (list != null && list.size() > 0) {
                if (dto.getStudentIdList() != null && dto.getStudentIdList().size() > 0) {
                    List<StudentStudyTimeTecordVo> result = new ArrayList<>();
                    for (StudentStudyTimeTecordVo studentStudyTimeTecordVo : list) {
                        if (dto.getStudentIdList().contains(studentStudyTimeTecordVo.getStudentId())) {
                            result.add(studentStudyTimeTecordVo);
                        }
                    }
                    downloadExcel(result, response);
                }

            }
        }

    }

    /**
     * 导出excel
     *
     * @param list
     * @param response
     */
    public void downloadExcel(List<StudentStudyTimeTecordVo> list, HttpServletResponse response) {
        String title = "考试成绩";
        Workbook workbook = writeDataToExcel(list);
        try {
            ExcelUtil.downloadExcel(response, workbook, title);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出Quizexcel
     *
     * @param list
     * @param response
     */
    public void downloadQuizExcel(List<StudentQuizRecordVo> list, HttpServletResponse response) {
        String title = "考试成绩";
        Workbook workbook = writeQuizDataToExcel(list);
        try {
            ExcelUtil.downloadExcel(response, workbook, title);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将数据写入excel
     *
     * @param list
     * @return
     */
    public Workbook writeQuizDataToExcel(List<StudentQuizRecordVo> list) {
        String[] titleList = {"姓名", "联系电话", "已学视频数", "随堂考分数", "获得学时"};
        InputStream is = Test.class.getClassLoader().getResourceAsStream("templates/studentQuiz.xlsx");
        //检查模板文件
        Workbook workbook = null;
        try {
            workbook = new XSSFWorkbook(is);
            if (workbook != null) {
                for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                    //获得当前sheet工作表
                    Sheet sheet = workbook.getSheetAt(sheetNum);
                    if (sheet == null) {
                        continue;
                    }
                    //获得当前sheet的结束行
                    int lastRowNum = sheet.getLastRowNum();
                    Row firstRow = sheet.getRow(lastRowNum - 1);
                    int columnNum = 0;
                    if (firstRow != null) {
                        columnNum = firstRow.getPhysicalNumberOfCells();
                    }
                    for (int j = 0; j < columnNum; j++) {
                        Cell cell = firstRow.getCell(j); //第1行,第j列
                        String cellValue = cell.getStringCellValue();
                        System.out.println(cellValue);
                    }
                    Row row = sheet.createRow(lastRowNum + 1);
                    //创建内容
                    Cell dataCell = null;
                    Long count = 0L;
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.createRow(lastRowNum + i + 1);
                        for (int j = 0; j < titleList.length; j++) {
                            dataCell = row.createCell(j);
                            if (j == 0) {
                                String value = list.get(i).getName();
                                dataFormat(dataCell, value);
                            } else if (j == 1) {
                                String value = list.get(i).getTel();
                                dataFormat(dataCell, value);
                            } else if (j == 2) {
                                Integer value = list.get(i).getQuizTimes();
                                dataFormat(dataCell, value);
                            } else if (j == 3) {
                                Double value = list.get(i).getGrade();
                                dataFormat(dataCell, value);
                            } else if (j == 4) {
                                Integer value = list.get(i).getClassHours();
                                dataFormat(dataCell, value);
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }


    /**
     * 将数据写入excel
     *
     * @param list
     * @return
     */
    public Workbook writeDataToExcel(List<StudentStudyTimeTecordVo> list) {
        String[] titleList = {"姓名", "联系电话", "已学视频数", "已学时长", "剩余学习时长"};
        InputStream is = Test.class.getClassLoader().getResourceAsStream("templates/studentStudyTimeTecord.xlsx");
        //检查模板文件
        Workbook workbook = null;
        try {
            workbook = new XSSFWorkbook(is);
            if (workbook != null) {
                for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                    //获得当前sheet工作表
                    Sheet sheet = workbook.getSheetAt(sheetNum);
                    if (sheet == null) {
                        continue;
                    }
                    //获得当前sheet的结束行
                    int lastRowNum = sheet.getLastRowNum();
                    Row firstRow = sheet.getRow(lastRowNum - 1);
                    int columnNum = 0;
                    if (firstRow != null) {
                        columnNum = firstRow.getPhysicalNumberOfCells();
                    }
                    for (int j = 0; j < columnNum; j++) {
                        Cell cell = firstRow.getCell(j); //第1行,第j列
                        String cellValue = cell.getStringCellValue();
                        System.out.println(cellValue);
                    }
                    Row row = sheet.createRow(lastRowNum + 1);
                    //创建内容
                    Cell dataCell = null;
                    Long count = 0L;
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.createRow(lastRowNum + i + 1);
                        for (int j = 0; j < titleList.length; j++) {
                            dataCell = row.createCell(j);
                            if (j == 0) {
                                String value = list.get(i).getName();
                                dataFormat(dataCell, value);
                            } else if (j == 1) {
                                String value = list.get(i).getTel();
                                dataFormat(dataCell, value);
                            } else if (j == 2) {
                                Integer value = list.get(i).getLearnCount();

                                dataFormat(dataCell, value);
                            } else if (j == 3) {
                                String value = "";
                                Integer seconds = list.get(i).getPlayDuration();
                                if (seconds != null) {
                                    int min = seconds / 60;
                                    int second = seconds % 60;
                                    value = min + "分钟" + second + "秒";
                                }
                                dataFormat(dataCell, value);
                            } else if (j == 4) {
                                String value = "";
                                Integer seconds = list.get(i).getSurplusDuration();
                                if (seconds != null) {
                                    int min = seconds / 60;
                                    int second = seconds % 60;
                                    value = min + "分钟" + second + "秒";
                                }
                                dataFormat(dataCell, value);
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    /**
     * 单元格值格式化
     *
     * @param dataCell
     * @param obj
     */
    private static void dataFormat(Cell dataCell, Object obj) {
        if (obj == null) {
            dataCell.setCellValue("");
        } else {
            if (obj instanceof String) {
                dataCell.setCellValue((String) obj);
            } else if (obj instanceof Double) {
                dataCell.setCellValue((Double) obj);
            } else if (obj instanceof Float) {
                dataCell.setCellValue((Float) obj);
            } else if (obj instanceof Long) {
                dataCell.setCellValue((Long) obj);
            } else if (obj instanceof Integer) {
                dataCell.setCellValue((Integer) obj);
            } else if (obj instanceof Boolean) {
                dataCell.setCellValue((Boolean) obj);
            } else if (obj instanceof Date) {
                Date d = (Date) obj;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String createDate = sdf.format(d);
                dataCell.setCellValue(createDate);
            }
        }
    }

    /**
     * 学员随堂考记录列表
     *
     * @param orderId 主键
     * @return 单条数据
     */
    @GetMapping("/student-quiz-record-list/{orderId}")
    public AjaxResult selectQuizRecordByOrderId(@PathVariable Integer orderId, Pageable pageable) throws IOException, NoSuchAlgorithmException {
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<StudentQuizRecordVo> list = courseStudyTimeTecordService.selectQuizRecordByOrderId(orderId);
        PageInfo<StudentQuizRecordVo> result = new PageInfo<>(list);
        return AjaxResult.success(result);
    }


    /**
     * 企业所购买课程包学员随堂考记录列表(导出)
     *
     * @return
     */
    @PostMapping("/student-quiz-excel")
    public void downloadQuizExcel(@RequestBody StudentRecordExcelDto dto, HttpServletResponse response) {

        if (dto.getType() == 1) {
            List<StudentQuizRecordVo> list = courseStudyTimeTecordService.selectQuizRecordByOrderId(dto.getOrderId());
            downloadQuizExcel(list, response);
        } else {
            List<StudentQuizRecordVo> list = courseStudyTimeTecordService.selectQuizRecordByOrderId(dto.getOrderId());

            if (list != null && list.size() > 0) {
                if (dto.getStudentIdList() != null && dto.getStudentIdList().size() > 0) {
                    List<StudentQuizRecordVo> result = new ArrayList<>();
                    for (StudentQuizRecordVo studentQuizRecordVo : list) {
                        if (dto.getStudentIdList().contains(studentQuizRecordVo.getStudentId())) {
                            result.add(studentQuizRecordVo);
                        }
                    }
                    downloadQuizExcel(result, response);
                }

            }
        }

    }


}
